package com.struggle.myrabbitmq.sample.simple;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.DeliverCallback;
import com.struggle.myrabbitmq.sample.MyRabbitConstants;
import com.struggle.myrabbitmq.util.ConnectionUtil;

import java.io.IOException;

//import com.rabbitmq.client.QueueingConsumer;

/**
 * @className Receive
 * @Description 普通模式：rabbitMQ消费消息
 * @Author liuwj3
 * @Date 2019/9/19 0019 上午 11:20
 **/
public class Receive {

    public static void main(String[] args) throws IOException, InterruptedException {
        Connection connection = ConnectionUtil.getConnection();
        Channel channel = connection.createChannel();

        // 声明队列
        channel.queueDeclare(MyRabbitConstants.QUEUE_NAME_SIMPLE, false, false, false, null);

        // rabbitmq 3.4.1版本写法
        /*// 定义消费者
        QueueingConsumer consumer = new QueueingConsumer(channel);
        // 监听队列 b:true表示自动应答，false表示手动应答（channel.basicAck）
        channel.basicConsume(MyRabbitConstants.QUEUE_NAME_SIMPLE, true, consumer);
        while (true) {
            QueueingConsumer.Delivery delivery = consumer.nextDelivery();
            String message = new String(delivery.getBody());
            System.out.println(" [x] Received '" + message + "'");
        }*/

        // rabbitmq 4.x版本后写法
        DeliverCallback callback = (consumerTag, delivery) -> {
            String message = new String(delivery.getBody());
            System.out.println(" [x] Received '" + message + "'");
        };
        channel.basicConsume(MyRabbitConstants.QUEUE_NAME_SIMPLE, true, callback, consumerTag -> {});
    }
}
